package com.scoremg.aop;

import com.scoremg.annotation.GlobalInterceptor;
import com.scoremg.entity.contants.Constants;
import com.scoremg.entity.dto.WebSessionUserDto;
import com.scoremg.entity.enums.ResponseCodeEnum;
import com.scoremg.entity.enums.RoleTypeEnums;
import com.scoremg.exception.BusinessException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component("operationAspect")
public class OperationAspect {

    private static final Logger log = LoggerFactory.getLogger(OperationAspect.class);

    @Before("@annotation(com.scoremg.annotation.GlobalInterceptor)")
    public void interceptorDo(JoinPoint point) throws BusinessException {
        try{
            // 获取方法
            Method method = ((MethodSignature) point.getSignature()).getMethod();
            // 获取注解
            GlobalInterceptor interceptor = method.getAnnotation(GlobalInterceptor.class);
            if (interceptor == null) {
                return;
            }
            /**
             * 检验登录
             */
            if (interceptor.checkAdmin()||interceptor.checkLogin()) {
                checkLogin(interceptor.checkAdmin());
            }
        }catch (BusinessException e){
            log.error("全局拦截异常",e);
            throw e;
        }catch (Exception e){
            log.error("全局拦截异常",e);
            throw new BusinessException(ResponseCodeEnum.CODE_500);
        }catch (Throwable e){
            log.error("全局拦截器异常", e);
            throw new BusinessException(ResponseCodeEnum.CODE_500);
        }
    }
    void checkLogin(boolean admin){
        // 在springboot 中获取request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        WebSessionUserDto webSessionUserDto = (WebSessionUserDto) request.getSession().getAttribute(Constants.SESSION_KEY);

        if (webSessionUserDto==null){
            throw new BusinessException(ResponseCodeEnum.CODE_901);
        }
        if (admin&&!webSessionUserDto.getRoleType().equals(RoleTypeEnums.TEACHER.getType())){
            throw new BusinessException(ResponseCodeEnum.CODE_404);
        }
    }
}
